package com.lfy.moss.components;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;

public class ModernTextField extends JPanel {

    // 输入框类型枚举
    public enum FieldType {
        TEXT, PASSWORD, EMAIL, NUMBER, SEARCH
    }

    // 颜色定义
    private static final Color BACKGROUND_COLOR = new Color(45, 45, 48);
    private static final Color BORDER_COLOR = new Color(80, 80, 80);
    private static final Color FOCUS_BORDER_COLOR = new Color(0, 122, 255);
    private static final Color ERROR_BORDER_COLOR = new Color(231, 76, 60);
    private static final Color SUCCESS_BORDER_COLOR = new Color(46, 204, 113);
    private static final Color TEXT_COLOR = new Color(220, 220, 220);
    private static final Color PLACEHOLDER_COLOR = new Color(140, 140, 140);
    private static final Color LABEL_COLOR = new Color(180, 180, 180);

    // 组件
    private JTextField textField;
    private JPasswordField passwordField;
    private JLabel labelText;
    private JLabel iconLabel;
    private JLabel suffixIconLabel;
    private JComponent activeField;

    // 属性
    private String placeholder = "";
    private String labelStr = "";
    private FieldType fieldType = FieldType.TEXT;
    private boolean isError = false;
    private boolean isSuccess = false;
    private boolean showPassword = false;
    private Icon prefixIcon;
    private Icon suffixIcon;
    private int cornerRadius = 8;
    private boolean animateLabel = true;

    // 动画相关
    private Timer focusTimer;
    private Timer errorShakeTimer;
    private float focusProgress = 0.0f;
    private boolean isFocused = false;
    private int shakeOffset = 0;

    public ModernTextField() {
        this(FieldType.TEXT);
    }

    public ModernTextField(FieldType type) {
        this.fieldType = type;
        initComponent();
    }

    private void initComponent() {
        setLayout(new BorderLayout());
        setOpaque(false);
        setPreferredSize(new Dimension(280, 60));

        // 创建主输入面板
        JPanel inputPanel = createInputPanel();
        add(inputPanel, BorderLayout.CENTER);

        // 设置字体
        Font font = getSupportedChineseFont(Font.PLAIN, 14);
        if (textField != null) textField.setFont(font);
        if (passwordField != null) passwordField.setFont(font);
    }

    private JPanel createInputPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                paintBackground(g);
            }
        };
        panel.setLayout(new BorderLayout());
        panel.setOpaque(false);
        panel.setBorder(new EmptyBorder(8, 12, 8, 12));

        // 创建标签
        if (!labelStr.isEmpty()) {
            labelText = new JLabel(labelStr);
            labelText.setFont(getSupportedChineseFont(Font.PLAIN, 12));
            labelText.setForeground(LABEL_COLOR);
            panel.add(labelText, BorderLayout.NORTH);
        }

        // 创建输入区域
        JPanel inputArea = new JPanel(new BorderLayout(8, 0));
        inputArea.setOpaque(false);

        // 添加前缀图标
        if (prefixIcon != null) {
            iconLabel = new JLabel(prefixIcon);
            inputArea.add(iconLabel, BorderLayout.WEST);
        }

        // 创建输入字段
        createInputField();
        inputArea.add(activeField, BorderLayout.CENTER);

        // 添加后缀图标
        createSuffixIcon();
        if (suffixIconLabel != null) {
            inputArea.add(suffixIconLabel, BorderLayout.EAST);
        }

        panel.add(inputArea, BorderLayout.CENTER);
        return panel;
    }

    private void createInputField() {
        if (fieldType == FieldType.PASSWORD) {
            passwordField = new JPasswordField() {
                @Override
                protected void paintComponent(Graphics g) {
                    setOpaque(false);
                    super.paintComponent(g);
                }
            };
            setupField(passwordField);
            activeField = passwordField;
        } else {
            textField = new JTextField() {
                @Override
                protected void paintComponent(Graphics g) {
                    setOpaque(false);
                    super.paintComponent(g);
                }
            };
            setupField(textField);
            activeField = textField;
        }
    }

    private void setupField(JTextField field) {
        field.setOpaque(false);
        field.setBorder(null);
        field.setForeground(TEXT_COLOR);
        field.setCaretColor(FOCUS_BORDER_COLOR);
        field.setSelectionColor(FOCUS_BORDER_COLOR.darker());
        field.setSelectedTextColor(Color.WHITE);

        // 设置占位符
        setPlaceholder(field);

        // 添加事件监听器
        addFieldListeners(field);

        // 输入验证
        addInputValidation(field);
    }

    private void setPlaceholder(JTextField field) {
        if (!placeholder.isEmpty()) {
            field.putClientProperty("JTextField.placeholderText", placeholder);

            // 自定义占位符渲染（如果系统不支持）
            field.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    if (field.getText().equals(placeholder)) {
                        field.setText("");
                        field.setForeground(TEXT_COLOR);
                    }
                }

                @Override
                public void focusLost(FocusEvent e) {
                    if (field.getText().isEmpty()) {
                        field.setForeground(PLACEHOLDER_COLOR);
                        field.setText(placeholder);
                    }
                }
            });

            if (field.getText().isEmpty()) {
                field.setForeground(PLACEHOLDER_COLOR);
                field.setText(placeholder);
            }
        }
    }

    private void addFieldListeners(JTextField field) {
        field.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                isFocused = true;
                isError = false;
                startFocusAnimation(true);
                animateLabelUp();
            }

            @Override
            public void focusLost(FocusEvent e) {
                isFocused = false;
                startFocusAnimation(false);
                if (field.getText().isEmpty() || field.getText().equals(placeholder)) {
                    animateLabelDown();
                }
            }
        });

        field.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    fireActionEvent();
                }
            }
        });

        // 文本变化监听
        field.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                validateInput();
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                validateInput();
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                validateInput();
            }
        });
    }

    private void addInputValidation(JTextField field) {
        switch (fieldType) {
            case EMAIL:
                // 邮箱验证逻辑
                break;
            case NUMBER:
                // 数字验证逻辑
                field.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyTyped(KeyEvent e) {
                        char c = e.getKeyChar();
                        if (!Character.isDigit(c) && c != '.' && c != '-' && c != KeyEvent.VK_BACK_SPACE) {
                            e.consume();
                        }
                    }
                });
                break;
        }
    }

    private void createSuffixIcon() {
        if (fieldType == FieldType.PASSWORD) {
            // 密码显示/隐藏图标
            suffixIconLabel = new JLabel(createEyeIcon(false));
            suffixIconLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
            suffixIconLabel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    togglePasswordVisibility();
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    suffixIconLabel.setIcon(createEyeIcon(showPassword, true));
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    suffixIconLabel.setIcon(createEyeIcon(showPassword, false));
                }
            });
        } else if (fieldType == FieldType.SEARCH) {
            // 搜索图标
            suffixIconLabel = new JLabel(createSearchIcon());
        } else if (suffixIcon != null) {
            suffixIconLabel = new JLabel(suffixIcon);
        }
    }

    private void paintBackground(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int width = getWidth();
        int height = getHeight();

        // 应用震动效果
        if (shakeOffset != 0) {
            g2d.translate(shakeOffset, 0);
        }

        // 绘制背景
        g2d.setColor(BACKGROUND_COLOR);
        g2d.fill(new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius));

        // 绘制边框
        Color borderColor = getBorderColor();
        float borderWidth = isFocused ? 2.0f : 1.0f;

        // 动画边框效果
        if (focusProgress > 0) {
            // 混合颜色
            float r = BORDER_COLOR.getRed() + (FOCUS_BORDER_COLOR.getRed() - BORDER_COLOR.getRed()) * focusProgress;
            float ga = BORDER_COLOR.getGreen() + (FOCUS_BORDER_COLOR.getGreen() - BORDER_COLOR.getGreen()) * focusProgress;
            float b = BORDER_COLOR.getBlue() + (FOCUS_BORDER_COLOR.getBlue() - BORDER_COLOR.getBlue()) * focusProgress;
            borderColor = new Color(Math.round(r), Math.round(ga), Math.round(b));
            borderWidth = 1.0f + focusProgress;
        }

        g2d.setColor(borderColor);
        g2d.setStroke(new BasicStroke(borderWidth));
        g2d.draw(new RoundRectangle2D.Float(borderWidth/2, borderWidth/2,
                width - borderWidth, height - borderWidth, cornerRadius, cornerRadius));

        g2d.dispose();
    }

    private Color getBorderColor() {
        if (isError) return ERROR_BORDER_COLOR;
        if (isSuccess) return SUCCESS_BORDER_COLOR;
        if (isFocused) return FOCUS_BORDER_COLOR;
        return BORDER_COLOR;
    }

    private void startFocusAnimation(boolean focusIn) {
        if (focusTimer != null && focusTimer.isRunning()) {
            focusTimer.stop();
        }

        focusTimer = new Timer(20, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (focusIn) {
                    focusProgress += 0.1f;
                    if (focusProgress >= 1.0f) {
                        focusProgress = 1.0f;
                        focusTimer.stop();
                    }
                } else {
                    focusProgress -= 0.1f;
                    if (focusProgress <= 0.0f) {
                        focusProgress = 0.0f;
                        focusTimer.stop();
                    }
                }
                repaint();
            }
        });
        focusTimer.start();
    }

    private void animateLabelUp() {
        if (labelText != null && animateLabel) {
            labelText.setFont(getSupportedChineseFont(Font.PLAIN, 10));
            labelText.setForeground(FOCUS_BORDER_COLOR);
        }
    }

    private void animateLabelDown() {
        if (labelText != null && animateLabel) {
            labelText.setFont(getSupportedChineseFont(Font.PLAIN, 12));
            labelText.setForeground(LABEL_COLOR);
        }
    }

    private void startErrorShake() {
        if (errorShakeTimer != null && errorShakeTimer.isRunning()) {
            return;
        }

        final int[] shakePattern = {5, -5, 4, -4, 3, -3, 2, -2, 1, -1, 0};
        final int[] index = {0};

        errorShakeTimer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (index[0] < shakePattern.length) {
                    shakeOffset = shakePattern[index[0]++];
                    repaint();
                } else {
                    shakeOffset = 0;
                    errorShakeTimer.stop();
                    repaint();
                }
            }
        });
        errorShakeTimer.start();
    }

    private void togglePasswordVisibility() {
        showPassword = !showPassword;
        if (passwordField != null) {
            passwordField.setEchoChar(showPassword ? (char) 0 : '•');
            suffixIconLabel.setIcon(createEyeIcon(showPassword));
        }
    }

    private void validateInput() {
        String text = getText();
        isError = false;
        isSuccess = false;

        switch (fieldType) {
            case EMAIL:
                if (!text.isEmpty()) {
                    isError = !isValidEmail(text);
                    isSuccess = !isError;
                }
                break;
            case PASSWORD:
                if (!text.isEmpty()) {
                    isSuccess = isValidPassword(text);
                    isError = !isSuccess;
                }
                break;
        }

        repaint();
    }

    private boolean isValidEmail(String email) {
        return email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    }

    private boolean isValidPassword(String password) {
        // 简单密码验证：至少8位，包含字母和数字
        return password.length() >= 8 &&
                password.matches(".*[A-Za-z].*") &&
                password.matches(".*[0-9].*");
    }

    // 创建图标的方法
    private Icon createEyeIcon(boolean visible) {
        return createEyeIcon(visible, false);
    }

    private Icon createEyeIcon(boolean visible, boolean hover) {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                Color color = hover ? FOCUS_BORDER_COLOR : PLACEHOLDER_COLOR;
                g2d.setColor(color);
                g2d.setStroke(new BasicStroke(1.5f));

                if (visible) {
                    // 睁开的眼睛
                    g2d.drawOval(x + 2, y + 6, 16, 8);
                    g2d.fillOval(x + 8, y + 8, 4, 4);
                } else {
                    // 闭合的眼睛
                    g2d.drawOval(x + 2, y + 6, 16, 8);
                    g2d.fillOval(x + 8, y + 8, 4, 4);
                    g2d.drawLine(x + 2, y + 2, x + 18, y + 18);
                }

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 20; }

            @Override
            public int getIconHeight() { return 20; }
        };
    }

    private Icon createSearchIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                g2d.setColor(PLACEHOLDER_COLOR);
                g2d.setStroke(new BasicStroke(2f));
                g2d.drawOval(x + 2, y + 2, 12, 12);
                g2d.drawLine(x + 12, y + 12, x + 17, y + 17);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 20; }

            @Override
            public int getIconHeight() { return 20; }
        };
    }

    private Font getSupportedChineseFont(int style, int size) {
        String[] fontNames = {
                "Microsoft YaHei", "SimHei", "SimSun", "Dialog", "SansSerif"
        };

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] availableFonts = ge.getAvailableFontFamilyNames();

        for (String fontName : fontNames) {
            for (String availableFont : availableFonts) {
                if (availableFont.equals(fontName)) {
                    return new Font(fontName, style, size);
                }
            }
        }

        return new Font(Font.SANS_SERIF, style, size);
    }

    private void fireActionEvent() {
        ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "textFieldAction");
        for (ActionListener listener : getActionListeners()) {
            listener.actionPerformed(event);
        }
    }

    // 公共方法
    public String getText() {
        if (activeField instanceof JPasswordField) {
            char[] password = ((JPasswordField) activeField).getPassword();
            return new String(password);
        } else if (activeField instanceof JTextField) {
            String text = ((JTextField) activeField).getText();
            return text.equals(placeholder) ? "" : text;
        }
        return "";
    }

    public void setText(String text) {
        if (activeField instanceof JTextField) {
            ((JTextField) activeField).setText(text);
            ((JTextField) activeField).setForeground(TEXT_COLOR);
        }
    }

    public void setPlaceholder(String placeholder) {
        this.placeholder = placeholder;
        if (activeField instanceof JTextField) {
            setPlaceholder((JTextField) activeField);
        }
    }

    public void setLabel(String label) {
        this.labelStr = label;
        if (labelText != null) {
            labelText.setText(label);
        }
    }

    public void setError(boolean error) {
        this.isError = error;
        if (error) {
            startErrorShake();
        }
        repaint();
    }

    public void setSuccess(boolean success) {
        this.isSuccess = success;
        this.isError = false;
        repaint();
    }

    public void setPrefixIcon(Icon icon) {
        this.prefixIcon = icon;
    }

    public void setSuffixIcon(Icon icon) {
        this.suffixIcon = icon;
    }

    public void setFieldType(FieldType type) {
        this.fieldType = type;
    }

    public void addActionListener(ActionListener listener) {
        listenerList.add(ActionListener.class, listener);
    }

    public void removeActionListener(ActionListener listener) {
        listenerList.remove(ActionListener.class, listener);
    }

    public ActionListener[] getActionListeners() {
        return listenerList.getListeners(ActionListener.class);
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (activeField != null) {
            activeField.setEnabled(enabled);
        }
    }

    @Override
    public void requestFocus() {
        if (activeField != null) {
            activeField.requestFocus();
        }
    }
}
